﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RollbackEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RollbackEntry]
GO
CREATE PROCEDURE [dbo].[RollbackEntry]
    @queueEntryId int,
    @errorMsg nvarchar(max),
    @returnCode int output
AS 
    BEGIN
        SET NOCOUNT ON;

		SET @returnCode = 0
        BEGIN TRY
            UPDATE QueueEntry
            WITH (ROWLOCK)
            SET
				StateId = CASE WHEN DeliveryAttemptCount < MaxDeliveryAttemptCount THEN 1 ELSE 4 END,
				MachineName = NULL,
				ProcessId = NULL,
				ProcessorId = NULL,
				BatchId = NULL,
				DeliveryAttemptCount = DeliveryAttemptCount + 1,
				DeliveryTime = NULL,
				ErrorMessage = @errorMsg
			WHERE
				Id = @queueEntryId

        END TRY
        BEGIN CATCH
			SET @returnCode = 1

			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT @ErrorMessage = ERROR_MESSAGE(),
				   @ErrorSeverity = ERROR_SEVERITY(),
				   @ErrorState = ERROR_STATE();

			RAISERROR (@ErrorMessage, -- Message text.
					   @ErrorSeverity, -- Severity.
					   @ErrorState -- State.
					   );
       END CATCH
    END
GO